package grails.company

import grails.converters.JSON

class OrganizationController {
    def list() {
        def organizations = Organization.list()
        if (organizations) {
            render(contentType: 'text/json') {
                success = true
                data = organizations.collect {
                    [
                            'id': it.id,
                            'title': it.title,
                            'description' : it.description
                    ]
                }
            }
        } else {
            render(contentType: 'text/json') {
                success = false
            }
        }
    }

    def view() {
        if (!params?.data?.id) {
            list()
            return
        }

        def org = Organization.findById(params.data.id);
        if (org) {
            render(contentType: 'text/json') {
                success = true
                data = {
                    id = org.id
                    title = org.title
                    description = org.description
                }
            }
        } else {
            render(contentType: 'text/json') { success = false }
        }
    }

    def update() {
        if (!params?.data?.id || !params?.data?.title) {
            render(contentType: 'text/json') { success = false }
            return
        }

        def organization = Organization.findById(params.data.id);
        if (!organization) {
            render(contentType: 'text/json') { success = false }
            return
        }

        organization.properties['title', 'description'] = params.data
        if (!organization.validate()) {
            render(contentType: 'text/json') { success = false }
            return
        }

        organization.save()
        render(contentType: 'text/json') { success = true }
    }

    def delete() {
        if (!params?.data?.id) {
            render(contentType: 'text/json') { success = false }
            return
        }

        def org = Organization.findById(params.data.id);
        if (org) {
            org.delete()
            render(contentType: 'text/json') { success = true }
        } else {
            render(contentType: 'text/json') { success = false }
        }
    }

    def create() {
        if (!params?.data?.title) {
            render(contentType: 'text/json') { success = false }
            return
        }

        def organization = new Organization();
        organization.properties['title', 'description'] = params.data
        if (organization.validate() && organization.save()) {
            render(contentType: 'text/json') {
                success = true
                data = {
                    id = organization.id
                    title = organization.title
                    description = organization.description
                }
            }
        } else {
            render(contentType: 'text/json') { success = false }
        }
    }
}
